package leetcode;

class ListNode {
    int val;
    ListNode next;

    public ListNode(int val) {
        this.val = val;
    }
}

/**
 * Definition for singly-linked list.
 * public class ListNode {
 * int val;
 * ListNode next;
 * ListNode() {}
 * ListNode(int val) { this.val = val; }
 * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head1 = reverse(l1);
        ListNode head2 = reverse(l2);
        int count = 0;
        int gewei = 0;
        int shiwei = 0;
        ListNode node = null;
        ListNode newHead = null;
        ListNode cur = null;
        while (head1 != null && head2 != null) {
            gewei = (head1.val + head2.val + shiwei) % 10;
            shiwei = (head1.val + head2.val + shiwei) / 10;
            node = new ListNode(gewei);
            if (newHead == null) {
                newHead = node;
                cur = newHead;
            } else {
                cur.next = node;
                cur = node;
            }
            head1 = head1.next;
            head2 = head2.next;
        }
        if (head1 != null) {
            cur.next = head1;
        } else if (head2 != null) {
            cur.next = head2;
        }
        ListNode pre = reverse(newHead);
        return pre;
    }

    public ListNode reverse(ListNode head) {
        ListNode cur = head;
        ListNode pre = null;
        while (cur != null) {
            ListNode NEXT = cur.next;
            cur.next = pre;
            pre = cur;
            cur = NEXT;
        }
        return pre;
    }

    public void display(ListNode head) {
        ListNode cur = head;
        while (cur != null) {
            System.out.print(cur.val + " ");
            cur = cur.next;
        }
    }
}

public class Test2 {
    public static void main(String[] args) {
        ListNode head1 = new ListNode(7);
        ListNode node = new ListNode(2);
        ListNode node1 = new ListNode(4);
        ListNode node2 = new ListNode(3);

        ListNode head2 = new ListNode(5);
        ListNode node3 = new ListNode(6);
        ListNode node4 = new ListNode(4);

        head1.next = node;
        node.next = node1;
        node1.next = node2;
        head2.next = node3;
        node3.next = node4;

        Solution solution = new Solution();
        ListNode ret = solution.addTwoNumbers(head1, head2);
        solution.display(ret);
    }
}
